package com.zhuoya.healthcard.update;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInstaller;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;


import com.blankj.utilcode.util.Utils;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class UpdateUtil {

    /**
     * 获取序列号
     * @return 序列号
     */
    public static String getDeviceSerial() {
        String ret;
        try {
           Method systemProperties_get = Class.forName("android.os.SystemProperties").getMethod("get", String.class);
            ret=(String) systemProperties_get.invoke(null, "ro.serialno");
        } catch (Exception e) {
            e.printStackTrace();
            return "-1";
        }
        return ret;
    }


    //系统签名下静默安装
    public static boolean systemInstall( String apkPath) {
        Log.d("ss", apkPath);

        Class<?> pm = Utils.getApp().getPackageManager().getClass();
        try {
            if (Build.VERSION.SDK_INT >= 21) {
                Class<?> Install= Class.forName("android.app.PackageInstallObserver");
                Constructor<?> constructor = Install.getDeclaredConstructor();
                constructor.setAccessible(true);
                Object installObserver = constructor.newInstance();
                Method method = pm.getDeclaredMethod("installPackage", Uri.class, Install, int.class, String.class);
                method.setAccessible(true);
                method.invoke(Utils.getApp().getPackageManager(), Uri.fromFile(new File(apkPath)), installObserver, 2, null);
            } else {
                Method method = pm.getDeclaredMethod("installPackage", Uri.class, Class.forName("android.content.pm.IPackageInstallObserver"), int.class, String.class);
                method.setAccessible(true);
                method.invoke(Utils.getApp().getPackageManager(), Uri.fromFile(new File(apkPath)), null, 2, null);
            }
            return true;
        } catch (Exception e) {
            Log.e("error", e.getLocalizedMessage());
        }
        return false;
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static synchronized void uninstall(Context context, String pakckageName) {
        Intent intent = new Intent(context, context.getClass());
        PendingIntent sender = PendingIntent.getActivity(context, 0, intent, 0);
        PackageInstaller mPackageInstaller = context.getPackageManager().getPackageInstaller();
        mPackageInstaller.uninstall(pakckageName, sender.getIntentSender());
    }
}
